package com.ronsoft.books.nio.buffers;

import java.nio.CharBuffer;

/**
 * Buffer fill/drain example. This code uses the simplest * means of filling and
 * draining a buffer: one element at * a time.
 * 
 * @author Ron Hitchens (ron@ronsoft.com)
 */
public class BufferFillDrain {
	public static void main(String[] argv) throws Exception {
		CharBuffer buffer = CharBuffer.allocate(100);
		while (fillBuffer(buffer)) {
			//Flip()函数将一个能够继续添加数据元素的填充状态的缓冲区翻转成一个准备读出元素 的释放状态。
			buffer.flip();
			
			//
			drainBuffer(buffer);
			
			//一旦缓冲区对象完成填充并释放,它就可以被重新使用了。Clear()函数将缓冲区重置 为空状态。
			buffer.clear();
		}
	}

	private static void drainBuffer(CharBuffer buffer) {
		//记住在调用get( )之前必须查询缓冲区中的元素数量
		while (buffer.hasRemaining()) {
			//或者当 get()被调用时指出下一个元素应从何处检索。
			System.out.print(buffer.get());
		}
		System.out.println("");
	}

	private static boolean fillBuffer(CharBuffer buffer) {
		if (index >= strings.length) {
			return (false);
		}
		String string = strings[index++];
		for (int i = 0; i < string.length(); i++) {
			buffer.put(string.charAt(i));
		}
		return (true);
	}

	private static int index = 0;
	private static String[] strings = { "A random string value", "The product of an infinite number of monkeys",
			"Hey hey we're the Monkees", "Opening act for the Monkees: Jimi Hendrix", "'Scuse me while I kiss this fly", // Sorry
			"Help Me! Help Me!", };
}